﻿// <copyright file="EntityFrameworkMappingModelTemplate.cs" company="T4 Toolbox Team">
//  Copyright © T4 Toolbox Team. All Rights Reserved.
// </copyright>

namespace T4Toolbox.EntityFramework
{
    using System;
    using System.Data.Entity.Design;

    /// <summary>
    /// Generates Entity Framework mapping model.
    /// </summary>
    public class EntityFrameworkMappingModelTemplate : EntityFrameworkModelTemplate
    {
        /// <summary>
        /// Stores the XML generated by this template.
        /// </summary>
        private string mappingModel;

        /// <summary>
        /// Gets or sets the entity model generator instance.
        /// </summary>
        /// <value>
        /// An <see cref="EntityModelSchemaGenerator"/> with generated metadata.
        /// </value>
        public EntityModelSchemaGenerator EntityModelSchemaGenerator { get; set; }

        /// <summary>
        /// Gets the Entity Framework storage mapping model generated by this template.
        /// </summary>
        /// <value>
        /// A <see cref="String"/> that contains generated MSL in XML format.
        /// </value>
        public string MappingModel
        {
            get { return this.mappingModel; }
        }

        /// <summary>
        /// Generates mapping model.
        /// </summary>
        /// <returns>
        /// A <see cref="String"/> with generated XML.
        /// </returns>
        public override string TransformText()
        {
            this.WriteXml(this.EntityModelSchemaGenerator.WriteStorageMapping);
            this.mappingModel = this.GenerationEnvironment.ToString();
            return this.mappingModel;
        }

        /// <summary>
        /// Validates properties before code generation.
        /// </summary>
        protected override void Validate()
        {
            if (this.EntityModelSchemaGenerator == null)
            {
                throw new TransformationException("EntityModelSchemaGenerator property must be assigned");
            }
        }
    }
}
